<template>
  <div class="app-container">
    <el-row :gutter="20">
      <Title
        :show-btn="true"
        :is-show-back="false"
        name="应用管理"
        type="primary"
        btn-name="新建应用"
        icon-class="el-icon-plus"
        @btnClick="handleAdd"
      />
      <el-input
        placeholder="搜索应用名称"
        style="width: 220px; margin: 16px 0px"
        size="small"
        clearable
        v-model.trim="queryParams.applicationName"
        @keyup.enter.native="handleQuery"
      >
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-row :gutter="20">
        <!-- <div class="contentBox"> -->
        <el-col :span="4" :xs="24">
          <el-aside width="201px">
            <el-menu
              :default-active="defaultActive"
              text-color="#222222"
              :default-openeds="openeds"
              background-color="#fff"
              @select="onMenuSelect"
            >
              <template v-for="(item, index) in classifyList">
                <template v-if="item.second && item.second.length > 0">
                  <el-submenu :key="index" class="ban" :index="item.firstName">
                    <template #title>
                      <svg-icon
                        icon-class="icon_message"
                        style="
                          width: 12px;
                          height: 14px;
                          vertical-align: middle;
                          margin-right: 10px;
                        "
                      />
                      <span>{{ item.firstName }}</span>
                    </template>
                    <el-menu-item
                      v-for="(child, indx) in item.second"
                      :key="indx"
                      :index="child.categoryName"
                      :class="activeMenu == child.categoryName ? 'active' : ''"
                    >
                      <span>{{ child.categoryName }}</span>
                    </el-menu-item>
                  </el-submenu>
                </template>
              </template>
            </el-menu>
          </el-aside>
        </el-col>
        <el-col :span="20" :xs="24" style="padding-left: 35px">
          <div class="tableBox">
            <el-table v-loading="loading" :data="roleList" style="width: 100%">
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="50"
              />
              <el-table-column label="应用名称" prop="applicationName" />
              <el-table-column label="分类">
                <template slot-scope="scope">
                  <div>{{ siftingSort(scope.row.categoryId) || "-" }}</div>
                </template>
              </el-table-column>
              <el-table-column label="所属单位">
                <template slot-scope="scope">
                  <div>{{ scope.row.department || "-" }}</div>
                </template>
              </el-table-column>
              <el-table-column label="ip地址">
                <template slot-scope="scope">
                  <div>{{ scope.row.address || "-" }}</div>
                </template>
              </el-table-column>
              <el-table-column label="启用状态" width="100">
                <template slot-scope="scope">
                  <div>{{ scope.row.deleteFlag == 0 ? "启用" : "停用" }}</div>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                width="160"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="scope" v-if="scope.row.roleId !== 1">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['system:role:edit']"
                    >修改</el-button
                  >
                  <i
                    style="
                      display: inline-block;
                      height: 14px;
                      border-left: 2px solid #eaedf1;
                      margin: auto 11px;
                    "
                  />
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['system:role:remove']"
                    >删除</el-button
                  >
                  <i
                    style="
                      display: inline-block;
                      height: 14px;
                      border-left: 2px solid #eaedf1;
                      margin: auto 11px;
                    "
                  />
                  <el-dropdown
                    size="mini"
                    @command="(command) => handleCommand(command, scope.row)"
                    v-hasPermi="['system:role:edit']"
                  >
                    <span class="el-dropdown-link">
                      更多<i class="el-icon-caret-bottom"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item
                        command="applyCode"
                        v-hasPermi="['system:role:edit']"
                        >申码授权</el-dropdown-item
                      >
                      <el-dropdown-item
                        command="brightCode"
                        v-hasPermi="['system:role:edit']"
                        >亮码授权</el-dropdown-item
                      >
                      <el-dropdown-item
                        command="needCode"
                        v-hasPermi="['system:role:edit']"
                        >用码授权</el-dropdown-item
                      >
                      <el-dropdown-item
                        command="lookCode"
                        v-hasPermi="['system:role:edit']"
                        >查看授权</el-dropdown-item
                      >
                    </el-dropdown-menu>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>
            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </div>
        </el-col>
        <!-- </div> -->
      </el-row>
    </el-row>
    <!-- 用码授权对话框 -->
    <el-dialog
      :title="codeTitle"
      :visible.sync="openCode"
      width="556px"
      append-to-body
      class="dialogBox"
    >
      <div class="checkbox">
        <el-checkbox-group @change="changeCard" v-model="codeList">
          <el-checkbox v-for="obj in cardList" :label="obj.id" :key="obj.id">{{
            obj.cardName
          }}</el-checkbox>
        </el-checkbox-group>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCode">确 定</el-button>
        <el-button @click="cancelCode">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 查看授权对话框 -->
    <el-dialog
      title="查看授权"
      :visible.sync="lookCode"
      width="610px"
      append-to-body
      class="dialogBox"
      @close="getList"
    >
      <div class="box">
        <div class="useName">应用名称:{{ form.applicationName }}</div>
        <div class="privacy">
          <div>
            <span>Token&nbsp;&nbsp;:{{ applicationId }}</span>
            <svg-icon
              v-if="keyOpenEyes"
              @click="conceal('token', '闭眼')"
              icon-class="icon_see1"
              class="svg"
            />
            <svg-icon
              v-else
              @click="conceal('token', '睁眼')"
              icon-class="icon_see"
              class="svg"
            />
            <svg-icon
              @click="random('token')"
              icon-class="icon_refresh"
              class="svg"
            />
          </div>
          <div>
            <span>秘钥&nbsp;&nbsp;:{{ applicationKey }}</span>
            <svg-icon
              v-if="tokenOpenEyes"
              icon-class="icon_see1"
              @click="conceal('key', '闭眼')"
              class="svg"
            />
            <svg-icon
              v-else
              icon-class="icon_see"
              @click="conceal('key', '睁眼')"
              class="svg"
            />
            <svg-icon
              @click="random('key')"
              icon-class="icon_refresh"
              class="svg"
            />
          </div>
        </div>
        <div class="content">
          <div class="li">
            <li>申码授权</li>
            <div class="codeLi">
              <span v-for="(item, index) in applyCodeList" :key="index">{{
                item.cardName
              }}</span>
            </div>
          </div>
          <div class="li">
            <li>亮码授权</li>
            <div class="codeLi">
              <span v-for="(item, index) in brightCodeList" :key="index">{{
                item.cardName
              }}</span>
            </div>
          </div>
          <div class="li">
            <li>用码授权</li>
            <div class="codeLi">
              <span v-for="(item, index) in needCodeList" :key="index">{{
                item.cardName
              }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Title from "@/components/ShareTitle";
import {
  applicationQueryList,
  updateAppKey,
  applicationInfo,
  updateAppToken,
  deleteApplication,
  allCard,
  addRoleCard,
} from "@/api/system/application_management";
import { categoryAll } from "@/api/system/classified_management";
// import random from "@/utils/random.js";
export default {
  name: "applicationList",
  components: { Title },
  data() {
    return {
      userId: "",
      openeds: ["应用管理"],
      defaultActive: "生活",
      activeMenu: "生活",
      classifyList: [
        {
          firstName: "应用管理",
          second: [],
        },
      ],
      codeList: [],
      codeTitle: "",
      openCode: false,
      lookCode: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        applicationName: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        applicationName: [
          { required: true, message: "应用名称不能为空", trigger: "blur" },
        ],
        categoryId: [
          { required: true, message: "请选择应用分类", trigger: "change" },
        ],
        contactName: [
          { required: true, message: "联系人不能为空", trigger: "blur" },
        ],
        phoneNum: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
        ],
        orderNum: [
          { required: true, message: "排序号不能为空", trigger: "blur" },
        ],
        address: [
          { required: true, message: "IP地址不能为空", trigger: "blur" },
        ],
      },

      needCodeList: [],
      brightCodeList: [],
      applyCodeList: [],
      categoryList: [],
      applicationKey: "", // 应用的密钥
      applicationId: "", // 应用的token
      keyOpenEyes: true, // key是否睁眼
      tokenOpenEyes: true, // token是否睁眼
      statusOptions: [
        {
          value: "1",
          label: "启用",
        },
        {
          value: "0",
          label: "停用",
        },
      ],
      cardList: [], // 卡类型
    };
  },
  created() {
    this.userId = this.$store.state.user.userId;
    this.getList();
    this.getCardList();
    this.categoryAll();
  },
  methods: {
    /** 查询应用列表 */
    getList() {
      this.loading = true;
      applicationQueryList(
        this.addDateRange(this.queryParams, this.dateRange)
      ).then((response) => {
        this.roleList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },

    // 点击侧边栏搜索二级菜单内容
    onMenuSelect(e) {
      this.classifyList[0].second.forEach((item) => {
        if (item.categoryName === e) {
          this.queryParams.categoryId = item.id;
        }
      });
      this.getList();
    },
    // 查询所有分类
    categoryAll() {
      this.loading = true;
      categoryAll().then((response) => {
        this.categoryList = response.data;
        this.classifyList[0].second = response.data;
        // this.defaultActive = response.data[0].categoryName;
        // this.activeMenu = response.data[0].categoryName;
        // this.queryParams.categoryId = response.data[0].id;
        // this.getList();
      });
    },
    // 随机生成key或者token
    random(value) {
      if (value === "token") {
        updateAppToken(this.form).then((res) => {
          if (this.tokenOpenEyes) {
            this.applicationId = this.concealText(res.data.applicationId);
          } else {
            this.applicationId = res.data.applicationId;
          }
          this.form.applicationId = res.data.applicationId;
        });
      } else {
        updateAppKey(this.form).then((res) => {
          if (this.tokenOpenEyes) {
            this.applicationKey = this.concealText(res.data.applicationKey);
          } else {
            this.applicationKey = res.data.applicationKey;
          }
          this.form.applicationKey = res.data.applicationKey;
        });
      }
    },
    // 睁眼闭眼
    conceal(key, value) {
      switch (key) {
        case "token":
          this.keyOpenEyes = !this.keyOpenEyes;
          if (value === "闭眼") {
            this.applicationId = this.form.applicationId;
          } else {
            this.applicationId = this.concealText(this.form.applicationId);
          }
          break;
        case "key":
          this.tokenOpenEyes = !this.tokenOpenEyes;
          if (value === "闭眼") {
            this.applicationKey = this.form.applicationKey;
          } else {
            this.applicationKey = this.concealText(this.form.applicationKey);
          }
          break;
        default:
          break;
      }
    },
    // 隐藏数据
    concealText(tel) {
      var before = tel.substr(0, 4);
      var after = tel.substr(12, 4);
      return `${before}********${after}`;
    },

    // 用码选择观察
    changeCard() {
      // console.log(this.codeList, "this.codeList");
    },
    // 更多操作触发
    handleCommand(command, row) {
      this.codeList = [];
      switch (command) {
        case "applyCode":
          this.codeTitle = "申码授权";
          this.openCode = true;
          this.codeList = row.cardList.map((item) => {
            if (item.codeRole.status === 1) {
              return item.id;
            }
          });
          this.form = JSON.parse(JSON.stringify(row));
          break;
        case "brightCode":
          this.codeTitle = "亮码授权";
          this.openCode = true;
          this.codeList = row.cardList.map((item) => {
            if (item.codeRole.brightStatus === 1) {
              return item.id;
            }
          });
          this.form = JSON.parse(JSON.stringify(row));
          break;
        case "needCode":
          this.codeTitle = "用码授权";
          this.openCode = true;
          this.codeList = row.cardList.map((item) => {
            if (item.codeRole.useStatus === 1) {
              return item.id;
            }
          });
          this.form = JSON.parse(JSON.stringify(row));
          break;
        case "lookCode":
          this.form = JSON.parse(JSON.stringify(row));
          this.applicationKey = this.concealText(this.form.applicationKey);
          this.applicationId = this.concealText(this.form.applicationId);
          this.codeTitle = "查看授权";
          this.lookCode = true;
          this.needCodeList = [];
          this.brightCodeList = [];
          this.applyCodeList = [];
          row.cardList.map((item) => {
            if (item.codeRole.useStatus === 1) {
              var obj = item.codeRole;
              obj["cardName"] = item.cardName;
              this.needCodeList.push(obj);
            }
            if (item.codeRole.brightStatus === 1) {
              var obj = item.codeRole;
              obj["cardName"] = item.cardName;
              this.brightCodeList.push(obj);
            }
            if (item.codeRole.status === 1) {
              var obj = item.codeRole;
              obj["cardName"] = item.cardName;
              this.applyCodeList.push(obj);
            }
          });
          break;
        default:
          break;
      }
    },
    applicationInfo(row) {
      applicationInfo({ applicationId: row.applicationId }).then((response) => {
        this.form = response.data;
      });
    },
    // 提交code授权
    submitCode() {
      // 删除数组中的 undefined
      for (let i = 0; i < this.codeList.length; i++) {
        if (this.codeList[i] === undefined) {
          this.codeList.splice(i, 1);
        }
      }
      var cardList = JSON.parse(JSON.stringify(this.form.cardList));
      if (this.codeList.length < 1) {
        // 一个都没选中
        if (cardList.length < 1) {
          // 数组原来是空的
          this.$message.error("请选择要授权的码");
          return false;
        } else {
          // 数组原来有数据
          for (let i = 0; i < cardList.length; i++) {
            if (this.codeTitle === "申码授权") {
              cardList[i].codeRole.status = 0;
            } else if (this.codeTitle === "亮码授权") {
              cardList[i].codeRole.brightStatus = 0;
            } else if (this.codeTitle === "用码授权") {
              cardList[i].codeRole.useStatus = 0;
            }
            // cardList[i].codeRole.deleteFlag = 0; //测试
            cardList[i].updateId = this.userId;
            cardList[i].codeRole.updateId = this.userId;
          }
        }
      } else {
        // 数组有选中
        if (cardList.length < 1) {
          // 列表里面原来没有数据
          this.codeList.forEach((item) => {
            // 选中的
            this.cardList.forEach((ite) => {
              // 所有的码
              if (item === ite.id) {
                var obj = {
                  cardCode: ite.cardCode,
                  cardName: ite.cardName,
                  id: ite.id,
                  createId: this.userId,
                  deleteFlag: 0, //测试
                  codeRole: {
                    appId: this.form.id,
                    status: 0,
                    cardCode: ite.cardCode,
                    id: ite.id,
                    createId: this.userId,
                    brightStatus: 0,
                    useStatus: 0,
                    deleteFlag: 0, //测试
                  },
                };
                if (this.codeTitle === "申码授权") {
                  obj["codeRole"]["status"] = 1;
                } else if (this.codeTitle === "亮码授权") {
                  obj["codeRole"]["brightStatus"] = 1;
                } else if (this.codeTitle === "用码授权") {
                  obj["codeRole"]["useStatus"] = 1;
                }
                cardList.push(obj);
              }
            });
          });
        } else {
          // 里面原来有数据
          cardList.forEach((item, index) => {
            // 是否在选中的数组里面
            if (this.codeList.indexOf(item.id) !== -1) {
              // 存在
              if (this.codeTitle === "申码授权") {
                cardList[index].codeRole.status = 1;
              } else if (this.codeTitle === "亮码授权") {
                cardList[index].codeRole.brightStatus = 1;
              } else if (this.codeTitle === "用码授权") {
                cardList[index].codeRole.useStatus = 1;
              }
            } else {
              // 不存在
              if (this.codeTitle === "申码授权") {
                cardList[index].codeRole.status = 0;
              } else if (this.codeTitle === "亮码授权") {
                cardList[index].codeRole.brightStatus = 0;
              } else if (this.codeTitle === "用码授权") {
                cardList[index].codeRole.useStatus = 0;
              }
              cardList[index].deleteFlag = 0;
              cardList[index].codeRole.deleteFlag = 0; //测试
              cardList[index].updateId = this.userId;
              cardList[index].codeRole.updateId = this.userId;
            }
          });
          var old = cardList.map((item) => {
            return item.id;
          });
          this.codeList.forEach((item) => {
            if (old.indexOf(item) !== -1) {
              // 存在啥也不做 上面已经做过了
            } else {
              // 不存在
              this.cardList.forEach((ite) => {
                // 所有的码
                if (item === ite.id) {
                  var obj = {
                    cardCode: ite.cardCode,
                    cardName: ite.cardName,
                    id: ite.id,
                    createId: this.userId,
                    deleteFlag: 0,
                    codeRole: {
                      appId: this.form.id,
                      status: 0,
                      cardCode: ite.cardCode,
                      id: ite.id,
                      createId: this.userId,
                      brightStatus: 0,
                      useStatus: 0,
                      deleteFlag: 0, //测试
                    },
                  };
                  if (this.codeTitle === "申码授权") {
                    obj["codeRole"]["status"] = 1;
                  } else if (this.codeTitle === "亮码授权") {
                    obj["codeRole"]["brightStatus"] = 1;
                  } else if (this.codeTitle === "用码授权") {
                    obj["codeRole"]["useStatus"] = 1;
                  }
                  cardList.push(obj);
                }
              });
            }
          });
        }
      }
      let obj = {};
      // 去重
      let peon = cardList.reduce((cur, next) => {
        obj[next.cardCode] ? "" : (obj[next.cardCode] = true && cur.push(next));
        return cur;
      }, []); //设置cur默认类型为数组，并且初始值为空的数组
      this.form.cardList = peon;
      this.form["cardCode"] = "1";
      delete this.form.createTime; //true   删除字段时间
      delete this.form.updateTime; //true   删除字段时间
      addRoleCard(this.form).then((res) => {
        this.openCode = false;
        this.getList();
      });
    },
    cancelCode() {
      this.openCode = false;
    },
    // 查询卡类型
    getCardList() {
      this.loading = true;
      allCard().then((response) => {
        this.cardList = response.data;
      });
    },
    // 筛选分类
    siftingSort(id) {
      var name = "";
      this.categoryList.forEach((item) => {
        if (item.id === id) {
          return (name = item.categoryName);
        }
      });
      return name;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({
        path: "/addApplication",
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({
        path: "/updateApplication",
        query: {
          id: row.applicationId,
        },
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除应用名为"' + row.applicationName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return deleteApplication({ id: ids });
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss">
.contentBox {
  display: flex;
  width: 100%;
}
.tableBox {
  // width: calc(100vw - 200px);
  flex: 1;
  box-sizing: border-box;
  padding: 0px 10px 0px 20px;
}
.el-aside {
  border-right: 1px solid #e0e5f0;
  box-sizing: border-box;
  background-color: #fff;
  padding: 0;
  // min-height: calc(100vh + 50px);
  min-height: 100vh;
  border-right: 1px solid #ccc;
  ::v-deep.el-submenu__title i {
    color: #222222;
  }
  ::v-deep.el-menu-item {
    font-size: 12px;
  }
  ::v-deep.el-menu-item.is-active {
    background: linear-gradient(
      90deg,
      #fbfbfd 0%,
      #dfe5f1 100%,
      #cdd2dc 100%
    ) !important;
    color: #333;
  }
  .el-menu-item:hover,
  .el-menu-item:focus {
    background: linear-gradient(
      90deg,
      #fbfbfd 0%,
      #dfe5f1 100%,
      #cdd2dc 100%
    ) !important;
  }
  ::v-deep.el-submenu__title:hover,
  .el-submenu__title:focus {
    background: linear-gradient(
      90deg,
      #fbfbfd 0%,
      #dfe5f1 100%,
      #cdd2dc 100%
    ) !important;
  }
  .el-menu {
    border-right: none;
  }
  ::v-deep.el-submenu .el-submenu__title {
    color: #5d6470 !important;
  }
}
.dialogBox {
  ::v-deep.el-dialog__header {
    border-bottom: 1px solid #eaedf1 !important;
    ::v-deep.el-dialog__title {
      font-size: 16px !important;
    }
  }
}
// 遮罩居中
.dialogBox.el-dialog__wrapper {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .el-dialog__header {
    padding: 16px 20px 18px !important;
    border-bottom: 1px solid #eaedf1 !important;
  }
  .el-dialog__title {
    font-size: 16px !important;
  }
  .checkbox {
    background-color: #f4f5f9;
    width: 512px;
    box-sizing: border-box;
    padding: 14px 20px;
    height: 232px;
  }
  .el-dialog__body {
    padding: 14px 23px;
    border-bottom: 1px solid #eaedf1 !important;
  }
}
.box {
  font-size: 14px;
  color: #222222;
  span {
    margin-right: 10px;
  }
  .svg {
    width: 12px;
    height: 14px;
    vertical-align: middle;
    margin-right: 10px;
    cursor: pointer;
  }
  .useName {
    line-height: 22px;
  }
  .privacy {
    display: flex;
    justify-content: space-between;
    margin: 10px 0px;
  }
  .content {
    display: flex;
    .li {
      background-color: #f4f5f9;
      padding: 10px;
      margin-right: 12px;
      li {
        color: #5d6470;
      }
      .codeLi {
        background-color: #ffffff;
        width: 162px;
        height: 226px;
        margin: 4px auto 0px;
        box-sizing: border-box;
        padding: 10px 11px;
        span {
          display: block;
          margin-bottom: 8px;
        }
      }
    }
  }
}
</style>